package com.hou.shopping.product.exception;

import com.hou.shopping.exception.BizCodeEnume;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.hou.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有的异常
 */
//@ResponseBody  //为了用json跑出去
//@ControllerAdvice(basePackages ="com.hou.shopping.product.controller")
@RestControllerAdvice(basePackages ="com.hou.shopping.product.controller")
@Slf4j
public class ShoppingExceptionControllerAdvice {
//    数据校验的全局异常处理器
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现了问题{}，异常类型是：{}",e.getMessage(),e.getClass());
        BindingResult result=e.getBindingResult();
        Map<String,String> map=new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 全局异常处理器  未知异常处理
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        return  R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
